package com.ifast.album.service.impl;

import java.io.IOException;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ifast.album.dao.AlbumPhotoDao;
import com.ifast.album.domain.AlbumConf;
import com.ifast.album.domain.AlbumInfo;
import com.ifast.album.domain.AlbumPhoto;
import com.ifast.album.domain.AlbumPhotoMsg;
import com.ifast.album.service.AlbumConfService;
import com.ifast.album.service.AlbumInfoService;
import com.ifast.album.service.AlbumPhotoMsgService;
import com.ifast.album.service.AlbumPhotoService;
import com.ifast.common.utils.Const;
import com.ifast.common.utils.alioss.UploadResult;
import com.ifast.common.utils.alioss.UploadUtils;
import com.luculent.util.extension.api.PageResult;
import com.luculent.util.extension.api.Result;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;


/**
 * 
 * @author shíQíang㊚
 * @date 2019年4月9日09:56:53
 */
@Transactional
@Service("albumPhotoService")
public class AlbumPhotoServiceImpl extends ServiceImpl<AlbumPhotoDao, AlbumPhoto> implements AlbumPhotoService{
	
	@Autowired
	private AlbumInfoService albumInfoService;
	
	@Autowired
	private AlbumPhotoMsgService albumPhotoMsgService;
	
	@Autowired
	private AlbumConfService albumConfService;
	/**
	 * 试题分页查询
	 */
	@Override
	public PageResult<?> pageNormalList(String userId,String topDeptId,String albumId,String nian,String yue,String ri,Page<AlbumPhotoMsg> page) {
		
		return StringUtils.isBlank(albumId) ? PageResult.fail_msg("缺少必要参数") : 
			normalData2Page(userId,albumPhotoMsgService.selectPage(page, new EntityWrapper<AlbumPhotoMsg>()
		    		.eq("DW_CODE",topDeptId) 
		    		.eq("ALBUM_ID",albumId)
			    	.eq(StringUtils.isNotBlank(nian),"NIAN",nian).orderBy("NIAN",false)
			    	.eq(StringUtils.isNotBlank(yue),"YUE",yue).orderBy("YUE",false)
			    	.eq(StringUtils.isNotBlank(ri),"RI",ri).orderBy("RI",false)
			    	.orderBy("CREATE_TIME",false)));
	} 
	
	@Override
	public PageResult<?> pageLoopList(String userId, String dwCode,String nian, String yue,
			String ri, Page<AlbumPhoto> page,String url){
		if(StringUtils.isBlank(dwCode) || StringUtils.isBlank(userId) || dwCode.length() < Const.dwCodeSubLength){
			PageResult.fail_msg("缺少必要参数");
		}
		String topDeptCode = dwCode.substring(0, Const.dwCodeSubLength);
		AlbumConf conf = albumConfService.selectOne(new EntityWrapper<AlbumConf>().eq("DW_CODE", topDeptCode));
        //默认取五张
		page.setSize(Const.loops);
		if(conf == null || conf.getType().equals("0")){
        	//新增逻辑 
			List<String> dwCodeList = Lists.newArrayList();
			dwCodeList.add(dwCode.substring(0, Const.dwCodeSubLength/2)); //后台管理员
			dwCodeList.add(dwCode.substring(0, Const.dwCodeSubLength));	  //企业管理员
			
			List<String> albIdList = Lists.newArrayList();
			List<AlbumInfo> albums = albumInfoService.selectList(new EntityWrapper<AlbumInfo>().eq("DELFLAG", 0).eq("CLASSIFY", Const.album.album_loop.getId()).eq("DO_TYPE", Const.albumDoType.type_loop.getValue()).in("DW_CODE", dwCodeList));
    		if(CollectionUtil.isEmpty(albums)){
    			return checkIsEnough(page,url);
    		}
    		albIdList = albums.stream().map(alb -> alb.getId()).collect(Collectors.toList());
    		return loopData2Page(this.selectPage(page, new EntityWrapper<AlbumPhoto>()
    		    		.in("DW_CODE",dwCodeList)
    		    		.in("ALBUM_ID", albIdList) 
    			    	.eq(StringUtils.isNotBlank(nian),"NIAN",nian)
    			    	.eq(StringUtils.isNotBlank(yue),"YUE",yue)
    			    	.eq(StringUtils.isNotBlank(ri),"RI",ri)
    			    	.orderBy("DW_CODE",false)
    			    	.orderBy("NIAN",false)
    			    	.orderBy("YUE",false)
    			    	.orderBy("RI",false)
    			    	.orderBy("CREATE_TIME",false)),url);
        }else{
        	//原有的逻辑
        	AlbumInfo album = albumInfoService.selectOne(new EntityWrapper<AlbumInfo>().eq("DELFLAG", 0).eq("CLASSIFY", Const.album.album_loop.getId()).eq("DW_CODE", dwCode).eq("USER_ID",userId).andNew().eq("DO_TYPE", Const.albumDoType.type_nomal.getValue()).or().isNull("DO_TYPE"));
    		if(album == null){
    			return checkIsEnough(page,url);
    		}
    		return loopData2Page(this.selectPage(page, new EntityWrapper<AlbumPhoto>()
    		    		.eq("DW_CODE",dwCode) 
    		    		.eq("ALBUM_ID",album.getId())
    			    	.eq(StringUtils.isNotBlank(nian),"NIAN",nian).orderBy("NIAN",false)
    			    	.eq(StringUtils.isNotBlank(yue),"YUE",yue).orderBy("YUE",false)
    			    	.eq(StringUtils.isNotBlank(ri),"RI",ri).orderBy("RI",false)
    			    	.orderBy("CREATE_TIME",false)),url);
        }
	} 
	
	private  PageResult<?> checkIsEnough(Page<AlbumPhoto> pageAll,String url){
		PageResult<Map<String,Object>> pageRes = new PageResult<>(); 
		List<AlbumPhoto> photos = pageAll.getRecords();
		if(CollectionUtil.isEmpty(photos)){ 
			photos = Lists.newArrayList();
			for(int i=0;i<Const.loops;i++){
				photos.add(AlbumPhoto.builder().url(url+"img/album_loop.png").build());
			}
	    }else if(photos.size() < Const.loops){
			for(int i=0,total = Const.loops - photos.size();i<total;i++){
				photos.add(AlbumPhoto.builder().url(url+"img/album_loop.png").build());
			}
		}else if(photos.size() > Const.loops){
			photos = photos.subList(0, Const.loops);
		}
		List<Map<String,Object>> lm = Lists.newArrayList();
		photos.stream().forEach(msg ->{ 
			lm.add(BeanUtil.beanToMap(msg));
		}); 
		pageRes.setListData(lm);
	    pageRes.setPageNum(pageAll.getCurrent());
	    pageRes.setHasNext(pageAll.hasNext());
		return pageRes;
	} 
	
	private  PageResult<?> loopData2Page(Page<AlbumPhoto> pageAll,String url){
		return checkIsEnough(pageAll,url);
	}
	
	private  PageResult<?> normalData2Page(String userId,Page<AlbumPhotoMsg> pageAll){
		PageResult<Map<String,Object>> pageRes = new PageResult<>(); 
		if(CollectionUtil.isEmpty(pageAll.getRecords())){ 
			pageRes.setPageNum(1);
			pageRes.setHasNext(false);
	        return pageRes;
	    } 
		List<Map<String,Object>> datas = Lists.newArrayList();
		pageAll.getRecords().stream().forEach(msg ->{
			msg.setPhotos(this.selectList(new EntityWrapper<>(AlbumPhoto.builder().msgId(msg.getId()).build())));
			Map<String,Object> photo = BeanUtil.beanToMap(msg);  
			datas.add(photo);
		}); 
		Map<? extends String, ? extends Object> dataList = datas.stream().collect(Collectors.groupingBy(dayPhoto -> dayPhoto.get("dayTime").toString()));
		Map<String,Object> page = Maps.newHashMap();
		page.putAll(dataList);
		
		List<Map<String,Object>> lm = Lists.newArrayList();
		lm.add(page);
		pageRes.setListData(lm);
		pageRes.setPageNum(pageAll.getCurrent());
		pageRes.setHasNext(pageAll.hasNext());
		return pageRes; 
	}
	
//	@Override
//	public PageResult<?> pageUserLoopList(String userId, String dwCode,String nian, String yue,
//			String ri, Page<AlbumPhoto> page,String url){
//		//原有的逻辑
//    	AlbumInfo album = albumInfoService.selectOne(new EntityWrapper<AlbumInfo>().eq("DELFLAG", 0).eq("CLASSIFY", Const.album.album_loop.getId()).eq("DW_CODE", dwCode).eq("USER_ID",userId).andNew().eq("DO_TYPE", Const.albumDoType.type_nomal.getValue()).or().isNull("DO_TYPE"));
//		if(album == null){
//			return checkIsEnough(page,url);
//		}
//		return loopData2Page(this.selectPage(page, new EntityWrapper<AlbumPhoto>()
//		    		.eq("DW_CODE",dwCode) 
//		    		.eq("ALBUM_ID",album.getId())
//			    	.eq(StringUtils.isNotBlank(nian),"NIAN",nian).orderBy("NIAN",false)
//			    	.eq(StringUtils.isNotBlank(yue),"YUE",yue).orderBy("YUE",false)
//			    	.eq(StringUtils.isNotBlank(ri),"RI",ri).orderBy("RI",false)
//			    	.orderBy("CREATE_TIME",false)),url);
//	} 
	
	@Override
	public PageResult<?> pageUserLoopList(String userId, String dwCode,String nian, String yue,
			String ri, Page<AlbumPhoto> page,String url){
		AlbumInfo album = albumInfoService.selectOne(new EntityWrapper<AlbumInfo>().eq("DELFLAG", 0).eq("CLASSIFY", Const.album.album_loop.getId()).eq("DW_CODE", dwCode).eq("USER_ID",userId).andNew().eq("DO_TYPE", Const.albumDoType.type_nomal.getValue()).or().isNull("DO_TYPE"));
		if(album == null){
			PageResult<?> pr = new PageResult<>();
			pr.setPageNum(1);
			pr.setHasNext(false);
			return  pr;
		}
		return userLoopData2Page(userId,this.selectPage(page, new EntityWrapper<AlbumPhoto>()
		    		.eq("DW_CODE",dwCode) 
		    		.eq("ALBUM_ID",album.getId())
			    	.eq(StringUtils.isNotBlank(nian),"NIAN",nian).orderBy("NIAN",false)
			    	.eq(StringUtils.isNotBlank(yue),"YUE",yue).orderBy("YUE",false)
			    	.eq(StringUtils.isNotBlank(ri),"RI",ri).orderBy("RI",false)
			    	.orderBy("CREATE_TIME",false)));
	}
	
	private  PageResult<?> userLoopData2Page(String userId,Page<AlbumPhoto> pageAll){
		PageResult<Map<String,Object>> pageRes = new PageResult<>(); 
		if(CollectionUtil.isEmpty(pageAll.getRecords())){ 
			PageResult<?> pr = new PageResult<>();
			pr.setPageNum(1);
			pr.setHasNext(false);
			return  pr;
	    }  
		List<Map<String,Object>> listData = Lists.newArrayList();
		pageAll.getRecords().stream().forEach(msg ->{ 
			listData.add(BeanUtil.beanToMap(msg)); 
		}); 
		pageRes.setListData(listData);
		pageRes.setPageNum(pageAll.getCurrent());
		pageRes.setHasNext(pageAll.hasNext());
		return pageRes; 
	}
	
	
	@Override
	public Result<?> cover(String albumId,String photoId){
		
		if(StringUtils.isBlank(albumId) || StringUtils.isBlank(photoId) )
			return Result.fail_msg("缺少必要参数");
		
		AlbumInfo album = albumInfoService.selectById(albumId); 
		if(album == null) 
			return Result.fail_msg("相册不存在");
		
		AlbumPhoto photo = this.selectById(photoId);
		if(photo == null) 
			return Result.fail_msg("照片不存在"); 
		 
		return albumInfoService.updateById(album.setCoverUrl(photo.getUrl()))?Result.ok():Result.fail_msg("相册更新失败");
	}
	@Override
	public Result<?> uploadAdmin(String userId, String dwCode, String albumId, String msg,
			HttpServletRequest request) throws IOException {
		if(StringUtils.isBlank(albumId))
			return Result.fail_msg("缺少必要参数");
		
		if(userMaxAlbumSize(userId))
			return Result.fail_msg("用户空间不足");
		
		AlbumInfo album = albumInfoService.selectById(albumId); 
		if(album == null) 
			return Result.fail_msg("相册不存在"); 
		
		if(album.getAlbumSize().intValue() > Const.everyAlbumSize )
			return Result.fail_msg("相册空间不足"); 
		
		List<AlbumPhoto> photos = doUpMulti(userId,dwCode,albumId,msg,request);
		if(CollectionUtil.isEmpty(photos))
			return Result.fail_msg("请上传图片"); 
		
		return upAlbumInfo(album,photos);
	}
	@Override
	public Result<?> upload(String userId,String dwCode,String albumId,String msg, HttpServletRequest request) throws IOException {
		
		if(StringUtils.isBlank(albumId))
			return Result.fail_msg("缺少必要参数");
		
		if(userMaxAlbumSize(userId))
			return Result.fail_msg("用户空间不足");
		
		AlbumInfo album = albumInfoService.selectById(albumId); 
		if(album == null) 
			return Result.fail_msg("相册不存在"); 
		
		if(album.getAlbumSize().intValue() > Const.everyAlbumSize )
			return Result.fail_msg("相册空间不足"); 
		
		List<AlbumPhoto> photos = doUpMulti(userId,dwCode,albumId,msg,request);
		if(CollectionUtil.isEmpty(photos))
			return Result.fail_msg("请上传图片"); 
		
		return upAlbumInfo(album,photos);
	}
	
	/**新增照片的说明*/
	private AlbumPhotoMsg addPhotoMsg(String userId,String dwCode,String albumId,String msg,Calendar calendar){
		AlbumPhotoMsg photoMsg = AlbumPhotoMsg.builder()
				.userId(userId)
				.dwCode(dwCode)
				.albumId(albumId)
				.msg(msg)
				.nian(calendar.get(Calendar.YEAR))
         		.yue(calendar.get(Calendar.MONTH)+1)
         		.ri(calendar.get(Calendar.DAY_OF_MONTH))
         		.dayTime(DateUtil.today())
				.build();
		albumPhotoMsgService.insert(photoMsg);
		return photoMsg;
	} 
	/**编辑照片的说明 */
	private boolean editPhotoMsg(String msgId,String msg){
		AlbumPhotoMsg photoMsg = albumPhotoMsgService.selectById(msgId);
		if(photoMsg == null)
			return false; 
		return albumPhotoMsgService.updateById(photoMsg.setMsg(msg));
	}
	/**删除照片的说明 */
	private boolean removePhotoMsg(String msgId){ 
		if(StringUtils.isBlank(msgId))
			return false;
		//没有照片了
		if(this.selectCount(new EntityWrapper<>(AlbumPhoto.builder().msgId(msgId).build())) > 0)
			return false;
		return albumPhotoMsgService.deleteById(msgId);
	}
	
	@Override
	public Result<?> upload(Const.album albumType,String userId,String deptId,String dwCode,String msg,HttpServletRequest request) throws IOException {
		
		AlbumInfo album = albumInfoService.selectOne(new EntityWrapper<AlbumInfo>().eq("DELFLAG", 0).eq("CLASSIFY", Const.album.album_loop.getId()).eq("DW_CODE", dwCode).eq("USER_ID",userId).andNew().eq("DO_TYPE", Const.albumDoType.type_nomal.getValue()).or().isNull("DO_TYPE"));
		if(album == null){
			album = albumInfoService.createAlbum(albumType, userId,deptId, dwCode,"轮播图相册", 0 , Const.albumDoType.type_nomal.getValue()); 
			if(album == null){
				return Result.fail_msg("创建相册失败"); 
			}
		} 	
		
		if(userMaxAlbumSize(userId))
			return Result.fail_msg("用户空间不足");
		
		if(album.getAlbumSize().intValue() > Const.everyAlbumSize )
			return Result.fail_msg("相册空间不足"); 
		
		List<AlbumPhoto> photos = doUpMulti(userId,dwCode,album.getId(),msg,request);
		if(CollectionUtil.isEmpty(photos))
			return Result.fail_msg("请上传图片");  
		
		return upAlbumInfo(album,photos);
	}
	
	private Result<?> upAlbumInfo(AlbumInfo album,List<AlbumPhoto> photos){
		return albumInfoService.updateById(album
				.setTotal(album.getTotal()+photos.size())
				.setAlbumSize(album.getAlbumSize() + photos.parallelStream()
				.mapToInt(AlbumPhoto::getPhotoSize)
				.sum()))?Result.ok():Result.fail_msg("相册更新失败");
	}
	/**
	 * 保存照片
	 */
	public List<AlbumPhoto> doUpMulti(String userId,String dwCode,String albumId,String msg,HttpServletRequest request) throws IOException{
		UploadResult result = UploadUtils.uploadOssPic(request);
        List<AlbumPhoto> photos = Lists.newArrayList();
		if(result.isSuccess() && CollectionUtil.isNotEmpty(result.getUrlAndSize())){
			Calendar calendar = Calendar.getInstance();  
			//添加留言
			AlbumPhotoMsg photoMsg = addPhotoMsg(userId,dwCode,albumId,msg,calendar);
			//添加图片 
        	for(int i=0,total=result.getUrlAndSize().size();i<total;i++){
        		Map<String,Object> map = result.getUrlAndSize().get(i);
        		for(String key : map.keySet()){
        			 photos.add(AlbumPhoto.builder()
                      		.albumId(albumId)
                     		.nian(calendar.get(Calendar.YEAR))
                     		.yue(calendar.get(Calendar.MONTH)+1)
                     		.ri(calendar.get(Calendar.DAY_OF_MONTH))
                     		.url(key)
                     		.sort(i)
                     		.msgId(photoMsg.getId())
                     		.photoSize(Long.valueOf(map.get(key).toString()).intValue())
                     		.userId(userId)
                     		.dwCode(dwCode)
                     		.build());
        		}
        	} 
        }
        this.insertBatch(photos);
        return photos;
	}
	/**
	 * 只编辑照片
	 */
	public AlbumPhoto doUpEdit(AlbumPhoto photo,HttpServletRequest request) throws IOException{
		UploadResult result = UploadUtils.uploadOssPic(request); 
		if(result.isSuccess() && CollectionUtil.isNotEmpty(result.getUrlAndSize())){  
			Map<String,Object> map = result.getUrlAndSize().get(0); 
    		for(String key : map.keySet()){
    			//删除老照片
    			UploadUtils.deletePic(photo.getUrl());
    			//换成新照片
    			photo = photo.setUrl(key).setPhotoSize(Long.valueOf(map.get(key).toString()).intValue()); 
    			this.updateById(photo);
    			break;
    		}
    	}
        return photo;
	}
	
	@Override
	public Result<?> remove(String photoId) {
		if(StringUtils.isBlank(photoId) )
			return Result.fail_msg("缺少必要参数");
		
		AlbumPhoto photo = this.selectById(photoId);
		if(photo == null) 
			return Result.fail_msg("照片不存在");
		
		AlbumInfo album = albumInfoService.selectById(photo.getAlbumId()); 
		if(album == null) 
			return Result.fail_msg("相册不存在");
		//删除相册封面
		if(photo.getUrl().equals(album.getCoverUrl()))
			album.setCoverUrl("");
		//更新相册数据
		albumInfoService.updateById(album.setTotal(album.getTotal() - 1).setAlbumSize(album.getAlbumSize() - photo.getPhotoSize()));
		//删除照片
		UploadUtils.deletePic(photo.getUrl());
		this.deleteById(photoId);
		//删除说明
		removePhotoMsg(photo.getMsgId());
		
		return Result.ok();
	}
	
	@Override
	public Result<?> editPhoto(String userId, String dwCode, String albumId, String photoId,
			HttpServletRequest request) throws IOException {
		
		if(StringUtils.isBlank(albumId) || StringUtils.isBlank(photoId))
			return Result.fail_msg("缺少必要参数");
		
		AlbumInfo album = albumInfoService.selectById(albumId); 
		if(album == null) 
			return Result.fail_msg("相册不存在"); 
		
		if(album.getAlbumSize().intValue() > Const.everyAlbumSize )
			return Result.fail_msg("相册空间不足");
		
		AlbumPhoto photo = this.selectById(photoId);
		if(photo == null) 
			return Result.fail_msg("照片不存在");
		//老的图片大小
		int oldPhotoSize = photo.getPhotoSize();
		
		AlbumPhoto photos = doUpEdit(photo,request);
		if(photos == null)
			return Result.fail_msg("图片删除失败");
		
		albumInfoService.updateById(album.setAlbumSize(album.getAlbumSize() - oldPhotoSize + photo.getPhotoSize()));
		//返回新的图片url
		Map<String,Object> map = Maps.newHashMap();
		map.put("url",photos.getUrl());
		return Result.ok(map);
	}
	/**
	 *  因为图片和msg不是一一对应关系，所以进行单独处理
	 */
	@Override
	public Result<?> editMsg(String userId, String dwCode, String msgId, String msg) {
		if(StringUtils.isBlank(msgId) || StringUtils.isBlank(msg))
			return Result.fail_msg("缺少必要参数");
		editPhotoMsg(msgId,msg);
		return Result.ok();
	}
	
	/**
	 * 用户拥有的空间大小
	 */
	private boolean userMaxAlbumSize(String userId){
		List<AlbumInfo> infos = albumInfoService.selectList(new EntityWrapper<>(AlbumInfo.builder().userId(userId).build()));
		if(CollectionUtil.isEmpty(infos))
			return false;
		if(infos.parallelStream().mapToInt(info -> info.getAlbumSize()).sum() < Const.maxAlbumSize)
			return false;
		return true;
	} 
	
}